package com.caijb.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author caijb
 * @version 1.0
 * @data 2025/8/28 17:00
 */
public class NettyServer {
    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        // 创建两个EventLoopGroup
        // bossGroup用于接受客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // workerGroup用于处理客户端连接的I/O操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建ServerBootstrap
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup)
                    // 指定服务端的通道类型
                    .channel(NioServerSocketChannel.class)
                    // 添加日志处理器
                    .handler(new LoggingHandler(LogLevel.INFO))
                    // 设置服务端Socket选项
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置客户端Socket选项
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 设置客户端连接的处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            // 添加字符串编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());

                            // 添加业务处理器
                            pipeline.addLast(new ServerHandler());
                        }
                    });

            // 绑定端口并启动服务
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("Netty Server started on port: " + port);

            // 等待服务端通道关闭
            future.channel().closeFuture().sync();
        } finally {
            // 优雅关闭EventLoopGroup
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyServer(8080).start();
    }

    // 业务处理器
    static class ServerHandler extends SimpleChannelInboundHandler<String> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("Client connected: " + ctx.channel().remoteAddress());
            ctx.writeAndFlush("Welcome to Netty Server! Type 'bye' to exit.\n");
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println("Received from " + ctx.channel().remoteAddress() + ": " + msg);

            // 处理退出命令
            if ("bye".equalsIgnoreCase(msg.trim())) {
                ctx.writeAndFlush("Goodbye!\n").addListener(ChannelFutureListener.CLOSE);
                return;
            }

            // 回显消息
            ctx.writeAndFlush("Echo: " + msg + "\n");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("Client disconnected: " + ctx.channel().remoteAddress());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.err.println("Exception caught: " + cause.getMessage());
            cause.printStackTrace();
            ctx.close();
        }
    }
}
